import { Gltf, GridProps, useAnimations, useGLTF } from "@react-three/drei"
import { GroupProps, PrimitiveProps, useFrame, useLoader } from "@react-three/fiber"
import { JSXElementConstructor, useEffect, useRef } from "react"
import { AnimationAction } from "three"
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"


export default function PlayAnimation(props: GroupProps & { state: string, src: string }) {

    const { scene, animations } = useLoader(GLTFLoader, props.src)
    const { actions, names } = useAnimations(animations, scene)
    const state = props.state == "assemble" ? true : props.state == "disassemble" ? false : null

    const disassaembleAnimations = names.filter((element) => element.includes("_disassemble"))
    const assaembleAnimations = names.filter((element) => element.includes("_assemble"))

    useEffect(() => {
        if (state)
            assemble(actions, assaembleAnimations, names)
        else
            disassemble(actions, disassaembleAnimations, names)
    }, [actions, names, state])

    useFrame(() => {
        console.log(names.filter((element) => element.includes("_disassemble")))
    })




    return (
        <group {...props}>
            <primitive object={scene} />
        </group>
    )
}

function disassemble(actions: { [x: string]: AnimationAction | null }, disassaembleAnimations: string[], names: string[]) {
    for (let i = 0; i < names.length; i++) {
        actions[names[i]]?.stop()
    }
    for (let i = 0; i < disassaembleAnimations.length; i++) {
        actions[disassaembleAnimations[i]]!.clampWhenFinished = true
        actions[disassaembleAnimations[i]]!.reset().play().setLoop(2200, 1)
    }
}
function assemble(actions: { [x: string]: AnimationAction | null }, assaembleAnimations: string[], names: string[]) {
    for (let i = 0; i < names.length; i++) {
        actions[names[i]]?.stop()
    }
    for (let i = 0; i < assaembleAnimations.length; i++) {
        actions[assaembleAnimations[i]]!.clampWhenFinished = true
        actions[assaembleAnimations[i]]!.reset().play().setLoop(2200, 1)
    }
}